package cool.taomu.toolkit.rpc.thrift.server.provider

import com.google.inject.Inject
import com.google.inject.Provider
import cool.taomu.toolkit.rpc.thrift.entity.ThriftConfig
import cool.taomu.toolkit.utils.NetworkInterfacesUtils
import java.net.InetSocketAddress
import java.util.List
import java.util.Map
import org.apache.thrift.protocol.TCompactProtocol
import org.apache.thrift.server.THsHaServer
import org.apache.thrift.server.THsHaServer.Args
import org.apache.thrift.transport.TNonblockingServerSocket
import org.apache.thrift.transport.layered.TFramedTransport
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

/**
 * Server
 */
@Accessors
class ThritfTHsHaArgsProvider implements Provider<Map<String, Args>> {
	val static LOG = LoggerFactory.getLogger(ThritfTHsHaArgsProvider);

	@Inject
	List<ThriftConfig> config;

	override get() {
		if (config !== null) {
			var server = config
			val configMap = <String, Args>newHashMap();
			server.forEach [
				configMap.put(it.name, getTHsHaArgs(it))
			]
			return configMap;
		}
	}

	private def getTHsHaArgs(ThriftConfig config) {
		if (config.networkInterfacesName !== null) {
			var nwInfo = NetworkInterfacesUtils.getNetworkInterfacesInfoByName(config.networkInterfacesName);
			config.host = nwInfo.ipv4;
		}
		var host = config.host;
		var port = config.port;
		var minWorkerThreads = config.minWorkerThreads
		var maxWorkerThreads = config.maxWorkerThreads
		LOG.info("启动服务 host:{},port:{}", host, port);
		LOG.info("minWorkerThreads:{},maxWorkerThreads:{}", minWorkerThreads, maxWorkerThreads);
		var socket = new TNonblockingServerSocket(new InetSocketAddress(host, port));
		var arg = new THsHaServer.Args(socket).minWorkerThreads(minWorkerThreads).maxWorkerThreads(maxWorkerThreads);
		arg.protocolFactory(new TCompactProtocol.Factory());
		arg.transportFactory(new TFramedTransport.Factory());
		return arg
	}

}
